package com.daoshu.mds.message.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

@Slf4j
@Component
public class SessionHandShakeInterceptor extends HttpSessionHandshakeInterceptor {
	
	@Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {	
		ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        String personId = req.getServletRequest().getParameter("personId");
        if(StringUtils.isEmpty(personId)){
        	 log.error("系统未授权用户,禁止登陆!");
        	 return false;
        }
        super.beforeHandshake(request, response, wsHandler, attributes);
        attributes.put("personId", personId);
        log.error("用户{}登录消息中心!",personId);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
    	ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        String personId = req.getServletRequest().getParameter("personId");
        log.error(personId + "链接成功");
    } 
}
